package fr.coupedumonde2014.app.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.Calendar;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;


import fr.coupedumonde2014.app.R;
import fr.coupedumonde2014.app.modele.Match;
import fr.coupedumonde2014.app.service.IBetService;
import fr.coupedumonde2014.app.session.SessionManager;

public class MatchView implements View.OnClickListener {

    public static boolean isAnimating = false;

    public interface DismissCallBack {
        public void dismiss(int position);
    }

    Context context;
    View view;
    Match match;

    View barreBas;

    TextView equipe1;
    TextView nul;
    TextView equipe2;
    TextView heure;
    TextView groupe;
    TextView stade;
    TextView ville;

    ImageView drapeauEquipe1;
    ImageView drapeauEquipe2;

    View boutonParierEqupe1;
    View boutonParierEqupe2;
    View boutonParierNul;

    int position;
    DismissCallBack dismissCallBack;

    public MatchView(Context context, View view, Match match, int position, DismissCallBack callBack) {
        this.context = context;
        this.view = view;
        this.match = match;
        this.position = position;
        this.dismissCallBack = callBack;

        this.construire(view);
    }

    public void construire(View view) {
        this.view = view;
        charger();
        remplir();

        if (match.getEquipeGagnante() > -1)
            afficherResultat();
        else
            ajouterListeners();
    }

    private void charger() {
        equipe1 = (TextView) view.findViewById(R.id.equipe1);
        nul = (TextView) view.findViewById(R.id.nul);
        equipe2 = (TextView) view.findViewById(R.id.equipe2);
        drapeauEquipe1 = (ImageView) view.findViewById(R.id.drapeaux1);
        drapeauEquipe2 = (ImageView) view.findViewById(R.id.drapeaux2);

        boutonParierEqupe1 = view.findViewById(R.id.parier1);
        boutonParierEqupe2 = view.findViewById(R.id.parier2);
        boutonParierNul = view.findViewById(R.id.parierNul);

        barreBas = view.findViewById(R.id.barreBas);

        heure = (TextView) view.findViewById(R.id.heure);
        groupe = (TextView) view.findViewById(R.id.groupe);
        stade = (TextView) view.findViewById(R.id.stade);
        ville = (TextView) view.findViewById(R.id.ville);
    }

    private void remplir() {

        if (match.getGroupe() != null)
            groupe.setText(context.getString(R.string.groupe) + " " + match.getGroupe());
        else
            groupe.setVisibility(View.GONE);

        if (match.getHeure() != null) {
            // Ajouter le décalage
            TimeZone myTimeZone = Calendar.getInstance().getTimeZone();
            Calendar myCalendar = Calendar.getInstance(myTimeZone);

            Calendar brasil = Calendar.getInstance(TimeZone.getTimeZone("America/Sao_Paulo"));


            int myHour = myCalendar.get(Calendar.HOUR_OF_DAY);
            int brasilHour = brasil.get(Calendar.HOUR_OF_DAY);
            int decalage = myHour - brasilHour;

            StringTokenizer heureToken = new StringTokenizer(match.getHeure(), ":");

            int heureLocale = Integer.parseInt(heureToken.nextToken());

            heure.setText((heureLocale + decalage) + ":" + heureToken.nextToken());
        } else
            heure.setVisibility(View.GONE);

        if (match.getStade() != null)
            stade.setText(match.getStade());
        else
            stade.setVisibility(View.GONE);

        if (match.getVille() != null)
            ville.setText(match.getVille());
        else
            ville.setVisibility(View.GONE);

        boolean isFr = Locale.getDefault().getLanguage().equals("fr");

        if (match.getEquipe1() != null) {
            if (match.equipe1.getNom() != null)
                if (isFr)
                    equipe1.setText(match.getEquipe1().getNom());
                else
                    equipe1.setText(match.getEquipe1().getName());

        }

        if (match.getEquipe2() != null) {
            if (match.getEquipe2().getNom() != null)
                if (isFr)
                    equipe2.setText(match.getEquipe2().getNom());
                else
                    equipe2.setText(match.getEquipe2().getName());
        }


        switch (match.getEquipePariee())

        {
            case 0:
                afficherNul();
                break;
            case 1:
                afficherEquipe1();
                break;
            case 2:
                afficherEquipe2();
                break;
            default:
                afficherVide();
        }
    }

    private void ajouterListeners() {
        drapeauEquipe1.setOnClickListener(this);
        boutonParierEqupe1.setOnClickListener(this);

        boutonParierNul.setOnClickListener(this);

        drapeauEquipe2.setOnClickListener(this);
        boutonParierEqupe2.setOnClickListener(this);
    }

    public View getView() {
        return view;
    }

    public void afficherResultat() {

        TextView points = (TextView) view.findViewById(R.id.points);
        points.setVisibility(View.VISIBLE);

        TextView score = (TextView) view.findViewById(R.id.score);
        score.setVisibility(View.VISIBLE);

        score.setText(match.getScore1() + "  -  " + match.getScore2());

        if (match.getEquipeGagnante() == match.getEquipePariee()) {
            barreBas.setBackground(context.getResources().getDrawable(R.drawable.gradient_gagne));
            points.setText("1pt !");
            points.setTextColor(context.getResources().getColor(R.color.gagne));
        } else {
            barreBas.setBackground(context.getResources().getDrawable(R.drawable.gradient_perdu));
            points.setText("0pt");
            points.setTextColor(context.getResources().getColor(R.color.perdu));
        }


        this.heure.setVisibility(View.GONE);
        view.findViewById(R.id.heureLocale).setVisibility(View.GONE);


    }

    public void afficherVide() {
        if (match.getEquipe1() != null && match.getEquipe2() != null) {

            afficherEquipe1();
            afficherEquipe2();
            afficherNul();

            if (match.getEquipe1().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe1().getDrapeau()).transform(new GrayScaleTransformation()).into(drapeauEquipe1);
            if (match.getEquipe2().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe2().getDrapeau()).transform(new GrayScaleTransformation()).into(drapeauEquipe2);
            drapeauEquipe1.setAlpha(0.4f);
            drapeauEquipe2.setAlpha(0.4f);

            equipe1.setAlpha(1f);
            nul.setAlpha(1f);
            equipe2.setAlpha(1f);
        }
    }

    public void afficherNul() {
        if (match.getEquipe1() != null && match.getEquipe2() != null) {
            if (match.getEquipe1().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe1().getDrapeau()).into(drapeauEquipe1);
            if (match.getEquipe2().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe2().getDrapeau()).into(drapeauEquipe2);
            drapeauEquipe1.setAlpha(1f);
            drapeauEquipe2.setAlpha(1f);

            equipe1.setAlpha(0.4f);
            nul.setAlpha(1f);
            equipe2.setAlpha(0.4f);
        }
    }

    public void afficherEquipe1() {
        if (match.getEquipe1() != null && match.getEquipe2() != null) {
            if (match.getEquipe1().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe1().getDrapeau()).into(drapeauEquipe1);
            if (match.getEquipe2().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe2().getDrapeau()).transform(new GrayScaleTransformation()).into(drapeauEquipe2);
            drapeauEquipe1.setAlpha(1f);
            drapeauEquipe2.setAlpha(0.4f);

            equipe1.setAlpha(1f);
            nul.setAlpha(0.4f);
            equipe2.setAlpha(0.4f);
        }
    }

    public void afficherEquipe2() {
        if (match.getEquipe1() != null && match.getEquipe2() != null) {
            if (match.getEquipe1().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe1().getDrapeau()).transform(new GrayScaleTransformation()).into(drapeauEquipe1);
            if (match.getEquipe2().getDrapeau() != null)
                Picasso.with(context).load(match.getEquipe2().getDrapeau()).into(drapeauEquipe2);
            drapeauEquipe1.setAlpha(0.4f);
            drapeauEquipe2.setAlpha(1f);

            equipe1.setAlpha(0.4f);
            nul.setAlpha(0.4f);
            equipe2.setAlpha(1f);
        }
    }

    @Override
    public void onClick(View view) {

        String equipeId = "0";
        if (!isAnimating) {
            switch (view.getId()) {
                case R.id.parier1:
                case R.id.drapeaux1:
                    equipeId = "1";
                    break;
                case R.id.drapeaux2:
                case R.id.parier2:
                    equipeId = "2";
                    break;
                case R.id.parierNul:
                    break;

            }
            new ParierTask().execute(match.getId(), equipeId);
        }
    }

    public class GrayScaleTransformation implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {

            final int height = source.getHeight();
            final int width = source.getWidth();

            final Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            final Canvas c = new Canvas(bmpGrayscale);
            final Paint paint = new Paint();
            final ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);
            final ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
            paint.setColorFilter(f);
            c.drawBitmap(source, 0, 0, paint);

            Bitmap result = bmpGrayscale;
            if (result != source) {
                source.recycle();
            }
            return result;
        }

        @Override
        public String key() {
            return "GrayScaleTransformation";
        }
    }

    public void animerPari(String s) {

        if (match.getEquipePariee() == -1) { //anime que la premiere fois
            dismissCallBack.dismiss(position);
        }

        int equipeId = Integer.parseInt(s);

        switch (equipeId) {
            case 0:
                afficherNul();
                break;
            case 1:
                afficherEquipe1();
                break;
            case 2:
                afficherEquipe2();
                break;
        }

        match.setEquipePariee(equipeId);

    }

    public class ParierTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... data) {

            String matchId = data[0];
            String equipeId = data[1];

            SessionManager sessionManager = new SessionManager(context);

            try {
                String id = sessionManager.getProfile().getId();
                return new IBetService().parier(id, matchId, equipeId);
            } catch (Exception e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null && !s.isEmpty())
                animerPari(s);
        }
    }
}
